package org.piggy.client.rpc.client;

import com.alibaba.fastjson2.JSONObject;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.piggy.client.rpc.handler.ClientHandler;
import org.piggy.common.async.RequestFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyClient {

    private final static Logger logger = LoggerFactory.getLogger(NettyClient.class);

    private static Channel channel;

    private static synchronized void init() {
        if(channel != null && channel.isActive()){
            return;
        }
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.group(new NioEventLoopGroup());
        bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

        bootstrap.handler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel ch) {
                ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                ch.pipeline().addLast(new StringDecoder());
                ch.pipeline().addLast(new ClientHandler());
                ch.pipeline().addLast(new LengthFieldPrepender(4, false));
                ch.pipeline().addLast(new StringEncoder());
            }
        });
        channel = bootstrap.connect("127.0.0.1",9000).syncUninterruptibly().channel();
    }

    public static Object sendRequest(RequestFuture request) {
        if(channel == null || !channel.isActive()){
            init();
        }
        String requestStr = JSONObject.toJSONString(request);
        channel.writeAndFlush(requestStr);
        logger.info("client request body==============" + requestStr);
        return request.waitResult();
    }

}
